import { defineStore } from 'pinia';
import apps from '@/pages/MainViews/app';

export const useRefreshStore = defineStore('refresh', {
    state: () => ({
        refreshTrigger: false,
        refreshType: '', // 标记刷新来源
        refreshTimeList: {} as Record<string, number>, // 各类型的最后刷新时间
    }),
    actions: {
        triggerRefresh(type: string) {
            if (this.queryRefresh(type)) {
                // 更新刷新状态
                this.refreshType = type;
                this.refreshTimeList[type] = Date.now(); // 更新该类型的最后刷新时间
                this.refreshTrigger = true; // 切换状态，触发监听
                console.log(`类型 ${type} 刷新触发成功`,this.refreshTrigger );
                if (type === 'PortalData') {
                    apps.FetchAvailablePortalData();
                }
            } else {
                this.refreshTrigger = false;
                console.log(`类型 ${type} 刷新间隔未到达5分钟，跳过刷新`);
                // uni.showToast({
                //     duration: 3500,
                //     icon: 'none',
                //     title: `5分钟内不要重复刷新, 请稍后重试`,
                // });
            }
        },
        queryRefresh(type: string) {
            const currentTime = Date.now();
            if (this.refreshTimeList[type]) {
                const lastRefreshTime = this.refreshTimeList[type] || 0;
                return currentTime - lastRefreshTime >= 5 * 60 * 1000;
            } else {
                return true
            }
        },
    },
});
